//
//  FirstViewController.m
//  protesteya
//
//  Created by Diego Martin Acosta Arreche on 9/14/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "ComplainsListController.h"
#import "DataAccess.h"

@interface ComplainsListController ()

@property (strong, nonatomic) TwitterInvoker *invoker;
@property GetTweetsListResponse *response;
@property UIRefreshControl* refreshControl;
@property NSMutableArray *tweetsList;
@property NSMutableArray *searchResults;
@property NSMutableDictionary *userImages;
@property (nonatomic,strong) DataAccess *dataAccess;

-(void) ProcessTweetList;
-(Complain*) CreateComplain:(NSDictionary *)tweet;


@end

@implementation ComplainsListController

-(DataAccess *)dataAccess
{
    if(_dataAccess == nil)
        _dataAccess = [[DataAccess alloc] init];
    
    return _dataAccess;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor colorWithWhite:0.8 alpha:0.9];
    
    UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [refresh addTarget:self action:@selector(refreshView:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    
    self.tweetsList = [[NSMutableArray alloc] init];
    self.userImages = [[NSMutableDictionary alloc] init];
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    
    [_invoker GetTweetsList];
}

- (NSString *)searchMessageForState:(TwitterSearchState)state
{
    switch (state)
    {
        case TwitterSearchStateLoading:
            return @"Cargando...";
            break;
        case TwitterSearchStateNotFound:
            return @"No se encontraron resultados";
            break;
        case TwitterSearchStateRefused:
            return @"Acceso a Twitter denegado";
            break;
        default:
            return @"No Disponible";
            break;
    }
}

-(void)refreshView:(UIRefreshControl *)refresh {
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Cargando..."];
    
    self.refreshControl = refresh;
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    [_invoker GetTweetsList];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM d, h:mm a"];
    NSString *lastUpdated = [NSString stringWithFormat:@"Última actualización %@", [formatter stringFromDate:[NSDate date]]];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
 }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [self.searchResults count];
    } else {
        NSUInteger count = [self.tweetsList count];
        return count > 0 ? count : 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ResultCellIdentifier = @"ResultCell";
    static NSString *ImageResultCellIdentifier = @"ImageResultCell";
    static NSString *LoadCellIdentifier = @"LoadingCell";
    
    NSUInteger count = [self.tweetsList count];
    if ((count == 0) && (indexPath.row == 0))
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LoadCellIdentifier];
        cell.textLabel.text = [self searchMessageForState:self.response.searchState];
        return cell;
    }
    
    Complain *complain;
    ComplainCell *cell;
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        complain = (self.searchResults)[indexPath.row];
    } else {
        complain = (self.tweetsList)[indexPath.row];
    }
    
    if(complain.image){
        cell = [self.tableView dequeueReusableCellWithIdentifier:ImageResultCellIdentifier];
        cell.picImageView.image = complain.image;
        cell.cellImageFavorite.hidden = !complain.isFavorite;
        cell.cellImageRetweeted.hidden = !complain.isRetweeted;
    }else{
        cell = [self.tableView dequeueReusableCellWithIdentifier:ResultCellIdentifier];        
        cell.cellNoImageFavorite.hidden = !complain.isFavorite;
        cell.cellNoImageRetweeted.hidden = !complain.isRetweeted;
    }
    
    cell.profileImageView.image = complain.userImage;
    cell.nameLabel.text = complain.user;
    cell.commentLabel.text = complain.text;
    cell.dateLabel.text = complain.date;
    cell.retweetedCountLabel.text = [NSString stringWithFormat:@"%d", complain.retweetedCount];
    cell.favoritedCountLabel.text = [NSString stringWithFormat:@"%d", complain.favoritedCount];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.tweetsList count]){
        Complain *complain;
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            complain = self.searchResults[indexPath.row];
        }
        else {
            complain = self.tweetsList[indexPath.row];
        }
        
        if (complain.image) {
            return 210;
        } else {
            return 102;
        }
    }else{
        return 210;
    }
}

-(void)getResponse:(NSDictionary *)response
{
    ResponseParser *parser = [[ResponseParser alloc] init];
    self.response = [parser ParseGetTweetsListResponse:(NSDictionary *)response];
    
    if(self.response.responseType == TwitterResponseError)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:self.response.errorMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    }
    else
    {
        [self ProcessTweetList];
        [self.refreshControl endRefreshing];
        [self.tableView reloadData];
        [self.tableView flashScrollIndicators];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        if(self.refreshControl)
            [self.refreshControl endRefreshing];
    }
    
    _invoker.tweeterInvokerDelegate = nil;
}

-(Complain*) CreateComplain:(NSDictionary *)tweet {
    
    NSDictionary* user = tweet[@"user"];
    
    Complain* complain = [[Complain alloc] init];
    
    complain.user = user[@"name"];
    
    NSString *tweetText = tweet[@"text"];
    NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray *matches = [detect matchesInString:tweetText options:0 range:NSMakeRange(0, [tweetText length])];
    for (NSTextCheckingResult *match in matches) {
        
        NSURL *url = [match URL];
        NSString *urlDescription = [url description];
        tweetText = [tweetText stringByReplacingOccurrencesOfString:urlDescription withString:@""];
    }
    complain.text = tweetText;
    
    complain.date = [tweet[@"created_at"] substringToIndex:16];
    
    UIImage* userImage = self.userImages[user[@"profile_image_url"]];
    if (userImage) {
        complain.userImage = userImage;
    }
    else
    {
        NSURL *url = [NSURL URLWithString: user[@"profile_image_url"]];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        UIImage *tmpImage = [[UIImage alloc] initWithData:data];
        self.userImages[user[@"profile_image_url"]] = tmpImage;
        complain.userImage = tmpImage;
    }
    
    NSDictionary *tweetEntities = tweet[@"entities"];
    NSArray *media = tweetEntities[@"media"];
    NSDictionary *media0 = media[0];
    NSString *media_url = media0[@"media_url"];
    media_url = [media_url stringByAppendingString:@":thumb"];
    NSURL *url = [NSURL URLWithString: media_url];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *tmpImage = [[UIImage alloc] initWithData:data];
    complain.image = tmpImage;

    complain.retweetedCount = (int)tweet[@"retweet_count"];
    complain.favoritedCount = (int)tweet[@"favourites_count"];
    
    Tweet *storeTweet = [self.dataAccess GetTweet:tweet[@"id"]];
    
    complain.isFavorite = storeTweet.favorite.boolValue;
    complain.isRetweeted = storeTweet.retweeted.boolValue;
    
    complain.tweet = tweet;
    
    return complain;
}

-(void) ProcessTweetList{
    self.tweetsList = [[NSMutableArray alloc] init];
    for (NSDictionary* tweet in self.response.tweetsList) {
        Complain* complain = [self CreateComplain:tweet];
        [self.tweetsList addObject:complain];
    }
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    self.searchResults = [[NSMutableArray alloc] init];
    searchText = [searchText lowercaseString];
    NSString *complainText;
    
    for(Complain *complain in self.tweetsList)
    {
        complainText = [complain.text lowercaseString];
        if([complainText rangeOfString:searchText].location != NSNotFound)
            [self.searchResults addObject:complain];
    }
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
    
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *indexPath;
    Complain *complain;

    
    if ([self.searchDisplayController isActive]) {
        indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
        if(self.searchResults.count > 0)
            complain = [self.searchResults objectAtIndex:indexPath.row];
    }
    else{
        indexPath = [self.tableView indexPathForSelectedRow];
        if(self.tweetsList.count > 0)
            complain = [self.tweetsList objectAtIndex:indexPath.row];
        
    }
       
    if(indexPath && complain)
    {
        [segue.destinationViewController setDetail:complain.tweet];
    }
}
@end
